/**
 * 按交易跳转集群设置
 */
angular.module('inspinia',['uiSwitch','infinity.angular-chosen']).controller("policyTargetCtrl", function($scope, $http, $state, $stateParams, i18nService,SweetAlert,$document) {
	$scope.paginationOptions=angular.copy($scope.paginationOptions);
	i18nService.setCurrentLang('zh-cn');

	$scope.mTimes=[];


	/*$scope.selectMTimeList = function(){
		$http.post('policyTarget/selectMTimeList', {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
		).success(function(result){
			$scope.mTimeList = result.data;
		}).error(function(){
		});
	};
	$scope.selectMTimeList();*/



	$scope.reset = function() {
		$scope.info = {vipCategory:null,vipCategoryType:null,nonCategory:null,nonCategoryType:null,transCategory:null,transCategoryType:null,
			startCreateDate:moment(new Date().getTime()-7*24*60*60*1000).format('YYYY-MM-DD'),endCreateDate:moment(new Date().getTime()).format('YYYY-MM-DD')};
		isVerifyTime = 1;
	};
    $scope.reset();

	//是否校验时间
	isVerifyTime = 1;//校验：1，不校验：0

	setBeginTime=function(setTime){
		console.log($scope.info.startCreateDate);
		$scope.info.startCreateDate = moment(setTime).format("YYYY-MM-DD");
		console.log($scope.info.startCreateDate);
	}

	setEndTime=function(setTime){
		$scope.info.endCreateDate = moment(setTime).format("YYYY-MM-DD");
	}


	$scope.vipCategories = [{text:"全部",value:null}, {text:"同旬同类",value:"1"},{text:"同旬不限类",value:"2"},{text:"不限旬不限类",value:"3"}];
	$scope.vipCategoryTypes = [{text:"全部",value:null}, {text:"最高值",value:"1"},{text:"平均值",value:"2"},{text:"最低值",value:"3"}];
	$scope.nonCategories = [{text:"全部",value:null}, {text:"同旬同类",value:"1"},{text:"同旬不限类",value:"2"},{text:"不限旬不限类",value:"3"}];
	$scope.nonCategoryTypes = [{text:"全部",value:null}, {text:"最高值",value:"1"},{text:"平均值",value:"2"},{text:"最低值",value:"3"}];
	$scope.transCategories = [{text:"全部",value:null}, {text:"同旬同类",value:"1"},{text:"同旬不限类",value:"2"},{text:"不限旬不限类",value:"3"}];
	$scope.transCategoryTypes = [{text:"全部",value:null}, {text:"最高值",value:"1"},{text:"平均值",value:"2"},{text:"最低值",value:"3"}];

	$scope.useStatuses = [{text:"未使用",value:"1"},{text:"已使用",value:"2"}];


	$scope.addOne = function(){
		var mTime = {"mTime": '', "floatStatus":'0'};
		$scope.mTimes.push(mTime);
	}

	$scope.openAddMTime = function(){
		$scope.selectMTimes();
		$('#addMTime').modal('show');
	}
	$scope.cancelAddMTime = function(){
		$('#addMTime').modal('hide');

	}


	$scope.targetConfig={'posConfig':{'status':0},'youXiangConfig':{'status':0}};
	$scope.openTargetConfig = function(){
		$http.post('policyTarget/selectTargetConfig', {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
		).success(function(result){
			$scope.targetConfig = result.data;
			$('#targetConfigModal').modal('show');
		}).error(function(){
		});

	}
	$scope.closeTargetConfig = function(){
		$('#targetConfigModal').modal('hide');
		$scope.targetConfig={'posConfig':{'status':0},'youXiangConfig':{'status':0}};
	}
	$scope.updateTargetConfig = function(){

		if($scope.targetConfig.policyTransRatioValue <= 0){
			$scope.notice("核心交易占比必须大于0");
			return;
		}
		if($scope.targetConfig.posConfig.floatAmount < 0 ){
			$scope.notice("向下浮动金额不能小于0");
			return;
		}

		if($scope.targetConfig.youXiangConfig.status){
			$scope.targetConfig.youXiangConfig.status = 1;
		}else {
			$scope.targetConfig.youXiangConfig.status=0;
		}
		if($scope.targetConfig.posConfig.status){
			$scope.targetConfig.posConfig.status = 1;
		}else {
			$scope.targetConfig.posConfig.status=0;
		}
		$scope.targetConfig.policyTransRatio = $scope.targetConfig.policyTransRatioValue/100;
		$http.post("policyTarget/updateTargetConfig", "info="+angular.toJson($scope.targetConfig),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
			.success(function(result){
				if(result.status){
					$scope.notice("操作成功");
					$scope.closeTargetConfig();
				} else {
					$scope.notice("操作失败");
				}
			}).error(function(){
		});
	}

	$scope.query = function() {
		$http.post('policyTarget/list',
       		 "info="+angular.toJson($scope.info)+"&pageNo="+$scope.paginationOptions.pageNo+"&pageSize="+$scope.paginationOptions.pageSize,
       		 {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
        ).success(function(data){
			$scope.policyTargetGrid.data = data.page.result;
			$scope.policyTargetGrid.totalItems = data.page.totalCount;

        }).error(function(){
        }); 
	};
	$scope.query();


	$scope.selectMTimes = function(){
		$http.post('policyTarget/selectMTimes', {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
			).success(function(result){
				$scope.mTimes = result.data;
			}).error(function(){
		});
	};
	$scope.selectMTimes();

	$scope.delrule = function (val,item) {
		if ( $scope.mTimes.length===1){
			$scope.notice("最后一条时间节点不允许删除");
			return;
		}
		$scope.mTimes.splice(val,1);
	}

	
	$scope.policyTargetGrid = {
	        paginationPageSize:10,                  //分页数量
	        paginationPageSizes: [10,20,50,100],	//切换每页记录数
	        useExternalPagination: true,		  //开启拓展名
	        columnDefs: [
				{field: 'createDate',displayName: '预估日期',width: 150,pinnable: false,sortable: false, cellFilter:'date:"yyyy-MM-dd"'},
				{field: 'mTime',displayName: '预估时间',width: 150,pinnable: false,sortable: false,cellFilter:'date:"HH:mm:ss"'},

				{field: 'vipCategory',displayName: 'VIP类别',width: 150,pinnable: false,sortable: false, cellFilter:"formatDropping:"+angular.toJson($scope.vipCategories)},
				{field: 'vipCategoryType',displayName: 'VIP类型',width: 150,pinnable: false,sortable: false, cellFilter:"formatDropping:"+angular.toJson($scope.vipCategoryTypes)},
				{field: 'forecastVipRatio',displayName: '预测VIP占比值',width: 150,pinnable: false,sortable: false},
				{field: 'actualVipRatio',displayName: '实际VIP占比值',width: 150,pinnable: false,sortable: false},
				{field: 'forecastVipAmount',displayName: '预估VIP交易量',width: 150,pinnable: false,sortable: false},
				{field: 'actualVipAmount',displayName: '实际VIP交易量',width: 150,pinnable: false,sortable: false},
				{field: 'timeActualVipAmount',displayName: 'VIP截止预估时间交易量',width: 150,pinnable: false,sortable: false},

				{field: 'nonCategory',displayName: '非优享类别',width: 150,pinnable: false,sortable: false, cellFilter:"formatDropping:"+angular.toJson($scope.nonCategories)},
				{field: 'nonCategoryType',displayName: '非优享类型',width: 150,pinnable: false,sortable: false, cellFilter:"formatDropping:"+angular.toJson($scope.nonCategoryTypes)},
				{field: 'forecastNonRatio',displayName: '预测非优享占比值',width: 150,pinnable: false,sortable: false},
				{field: 'actualNonRatio',displayName: '实际非优享占比值',width: 150,pinnable: false,sortable: false},
				{field: 'forecastNonAmount',displayName: '预估非优享交易量',width: 150,pinnable: false,sortable: false},
				{field: 'actualNonAmount',displayName: '实际非优享交易量',width: 150,pinnable: false,sortable: false},
				{field: 'timeActualNonAmount',displayName: '非优享截止预估时间交易量',width: 150,pinnable: false,sortable: false},


				{field: 'transCategory',displayName: '总量类别',width: 150,pinnable: false,sortable: false, cellFilter:"formatDropping:"+angular.toJson($scope.transCategories)},
				{field: 'transCategoryType',displayName: '总量类型',width: 150,pinnable: false,sortable: false, cellFilter:"formatDropping:"+angular.toJson($scope.transCategoryTypes)},
				{field: 'forecastTransRatio',displayName: '预测总量占比值',width: 150,pinnable: false,sortable: false},
				{field: 'actualTransRatio',displayName: '实际总量占比值',width: 150,pinnable: false,sortable: false},
				{field: 'forecastTransAmount',displayName: '预估总量交易量',width: 150,pinnable: false,sortable: false},
				{field: 'actualTransAmount',displayName: '实际总量交易量',width: 150,pinnable: false,sortable: false},
				{field: 'timeActualTransAmount',displayName: '总量截止预估时间交易量',width: 150,pinnable: false,sortable: false},

				{field: 'useStatus',displayName: '状态',width: 150,pinnable: false,sortable: false, cellFilter:"formatDropping:"+angular.toJson($scope.useStatuses)},
				{field: 'lastUpdateTime',displayName: '更新时间',width: 150,pinnable: false,sortable: false, cellFilter:'date:"yyyy-MM-dd HH:mm:ss"'},
				{field: 'bySource',displayName: '来源',width: 150,pinnable: false,sortable: false},

                {field: 'remark',displayName: '备注',width: 200,pinnable: false,sortable: false},
				{field: 'action',displayName: '操作',width: 150,pinnable: false,sortable: false,pinnedRight:true,
					cellTemplate:'<a class="lh30"  ng-click="grid.appScope.openDetail(row.entity.id)">详情</a>' +
					" <a ng-show='grid.appScope.hasPermit(\"policyTarget.save\") && row.entity.useStatus==1 && row.entity.sourceType == 1 ' ui-sref='org.policyTargetAdd({id:row.entity.id})'>修改 </a>" +
						'<a class="lh30" ng-show="grid.appScope.hasPermit(\'policyTarget.delete\') && row.entity.useStatus==1 && row.entity.sourceType == 1 " ng-click="grid.appScope.delete(row.entity.id)">删除</a>'
				},
	        ],
	        onRegisterApi: function(gridApi) {                
	            gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
	            	$scope.paginationOptions.pageNo = newPage;
	            	$scope.paginationOptions.pageSize = pageSize;
	            	$scope.query();
	            });
	        }
	};

	$scope.delete = function(){

	}

	$scope.delete = function(id){
		SweetAlert.swal({
				title: "是否要删除目标金额配置？",
				type: "warning",
				showCancelButton: true,
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "提交",
				cancelButtonText: "取消",
				closeOnConfirm: true,
				closeOnCancel: true },
			function (isConfirm) {
				if (isConfirm) {
					$http({
						url:"policyTarget/delete?id="+id,
						method:"POST"
					}).success(function(result){
						if(result.status){
							$scope.notice(result.msg);
							$scope.query();
						}else {
							$scope.notice(result.msg);
						}
					});

				}
			});
	}

	//详情弹框
	$scope.detailList=[];
	$scope.openDetail = function (id) {
		$http.get('policyTarget/detailList?id='+id).success(
			function (data) {
				$scope.detailList = data.list;
			});
		$('#detailModal').modal('show');
	}

	$scope.closeDetail = function(){
		$('#detailModal').modal('hide');
		$scope.detailList=[];
	}


	$scope.saveMTimes = function(){

		let flag = false;
		let flag2 = false;
		angular.forEach($scope.mTimes, function (e) {
			var arr = e.mTime.split(":");
			if(arr[0] < 9){
				flag = true;
			}
			if(arr[1] != '00'){
				flag2 = true;
			}
		});

		if(flag){
			$scope.notice("生效时间不能小于9:00");
			return;
		}

		if(flag2){
			$scope.notice("生效时间必须为整点");
			return;
		}

		SweetAlert.swal({
				title: "我已确认数据更新时间节点设置无误！",
				type: "warning",
				showCancelButton: true,
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				closeOnConfirm: true,
				closeOnCancel: true },
			function (isConfirm) {
				if (isConfirm) {
					$http.post("policyTarget/saveMTimes", $scope.mTimes)
						.success(function(result){
							if(result.status){
								$scope.notice("操作成功");
								$scope.cancelAddMTime();
							} else {
								$scope.notice(result.msg);
							}
						}).error(function(){
					});
				}
			});

	}
	
    // 导出
    $scope.export = function () {
        SweetAlert.swal({
                title: "确定导出吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true },
            function (isConfirm) {
                if (isConfirm) {
                    $scope.exportInfoClick("policyTarget/export",{"baseInfo":angular.toJson($scope.info)});
                }
            });
    };


	//页面绑定回车事件
	$document.bind("keypress", function(event) {
		$scope.$apply(function (){
			if(event.keyCode == 13){
				$scope.query();
			}
		})
	});
	
});